<!--suppress ALL -->
<template>
  <el-container id="folderPage" v-if="isRouterAlive">
    <el-aside>
      <div class="collection" @click="gotoMyCollection">
        <i class="fa fa-star" aria-hidden="true"></i>
        <span :class="isCollectClick? 'collect':''">我的收藏</span>
      </div>
      <el-tree
        highlight-current
        ref="tree2"
        node-key="id"
        lazy
        :empty-text="'文件夹加载中..'"
        :render-content="renderContent"
        :props="defaultProps"
        :data="dataFile"
        :accordion="true"
        :default-expanded-keys="expandedKeys"
        @node-click="handleNodeClick"
        @node-expand="handleNodeExpand"
        @node-collapse="handleNodeCollapse"
        :load="loadNode"
        v-if="isloaded"
      ></el-tree>
      <el-tree
        highlight-current
        ref="tree3"
        node-key="id"
        lazy
        :render-content="renderContent"
        :props="defaultProps"
        :data="workmateData"
        :default-expanded-keys="workmateExpandedKeys"
        @node-click="handleWorkmateClick"
        @node-collapse="handleWorkmateCollapse"
        @node-expand="handleWorkmateExpand"
        v-if="workmateisloaded"
        :load='loadedWFNode'
      ></el-tree>
      <el-tree
        highlight-current
        ref="tree4"
        node-key="id"
        lazy
        :render-content="renderContent"
        :props="defaultProps"
        :data="companyData"
        :load="loadCompanyNode"
        :default-expanded-keys="companyExpandedKeys"
        @node-click="handleCompanyClick"
        @node-expand="handleCompanyExpand"
        @node-collapse="handleCompanyCollapse"
        v-if="companyisloaded"
      ></el-tree>
      <!-- <el-tree
        highlight-current
        ref="tree5"
        node-key="id"
        lazy
        :render-content="renderContent"
        :props="defaultProps"
        :data="partnerData"
        :load="loadPartnerNode"
        :default-expanded-keys="partnerExpandedKeys"
        @node-click="handlePartnerClick"
        @node-expand="handlePartnerExpand"
        @node-collapse="handlePartnerCollapse"
        v-if="partnerisloaded"
      ></el-tree> -->
    </el-aside>
    <el-main>
      <file-details
        v-loading='tableLoading'
        v-if="isFileDetails"
        :currFileId="currFileId"
        :fileDetails="fileDetails"
        :nodeInfo="nodeInfo"
        :currNode="currNode"
        :resolveCallBack="resolveCallBack"
        :fileUrl="fileUrl"
        :keysForId="keysForId"
        :tempDirId="tempDirId"
        @goto="gotoByPath"
        @gotoByPathCom="gotoByPathCom"
        @gotoByPathPar="gotoByPathPar"
        @CellClick="CellClick"
        @loadedTheNode="loadedTheNode"
        @refreshTreeData="refreshTreeData"
        @handleParentNode="handleParentNode"
        @appendChildNode="appendChildNode"
        @reloadFolders="reloadFolders"
      ></file-details>
      <my-collection v-if="!isFileDetails"></my-collection>
    </el-main>
  </el-container>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex";
import FileDetails from "./file_details/FileDetails.vue";
import MyCollection from "./Colletions.vue";
var ipfsClient = require("ipfs-http-client");
export default {
  components: { FileDetails, MyCollection },
  provide() {
    return {
      reloadFileDetails: this.reloadFileDetails
    };
  },
  provide() {
    return {
      reload: this.reloadFolders
    };
  },
  provide() {
    return {
      setExpandedKeys: this.setExpandedKeys
    };
  },
  data() {
    return {
      isCollectClick: false,
      nodeInfo: {},
      expandedKeys: [],
      isFileDetails: true,
      isRouterAlive: true,
      tableLoading:false,
      dataFile: [
        {
          id: localStorage.getItem("dirId"),
          dirId: localStorage.getItem("dirId"),
          label: "我的文档",
          children: [],
          leaf: false
        }
      ],
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "leaf"
      },
      fileDetails: [],
      isFirst: true,
      resolveCallBack: null,
      isloaded: true,
      currFileId: localStorage.getItem("dirId"),
      currNode: [],
      nodeTemp: [],
      dataTemp: "",
      fileUrl: [],
      keysForId: [],
      workmateData: [
        {
          id: 0,
          dirId: 0,
          label: "同事共享",
          children: [],
          leaf: false,
          fileGold: []
        }
      ], // 同事共享树组件数据
      workmateExpandedKeys: [], //同事共享树组件默认展开节点
      companyData:[
        {
          id: 0,
          dirId: 0,
          label: "公司文档",
          children: [],
          leaf: false,
          fileGold: []
        }
      ],
      companyExpandedKeys: [],
      companyisloaded: true,
      // partnerData:[
      //   {
      //     id: 0,
      //     dirId: 0,
      //     label: "合作伙伴",
      //     children: [],
      //     leaf: false,
      //     fileGold: []
      //   }
      // ],
      partnerExpandedKeys: [],
      partnerisloaded: true,
      tempDirId: 0,
      workmateisloaded: true,
      searchNode: null,//给文件搜索用的节点
      folderId: '',//给文件搜索用的节点
    };
  },
  computed: {
    ...mapState(["fileObj", "userDirId", "theFile","canSearch"])
  },
  created() {
    this.$store.state.canSearch = false;
    this.getIpfs();
    this.setSearchInput("");
    sessionStorage.setItem("currentBox", "我的文档");
    this.$store.state.placeHolder = "搜索文件名称";
    this.$store.state.placeHolder = "搜索我的文档文件/文件夹";
  },
  mounted() {
  },
  destroyed() {},
  watch: {
    //不用箭头函数
    dataFile: function(newVal, oldVal) {
      if (newVal != oldVal) {
      }
    },
    fileDetails: function(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.reloadFileDetails();
        return this.fileDetails;
      }
    },
    appendChildNode: function(newVal, oldVal) {
      if (newVal !== oldVal) {
      }
    },
    nodeInfo: function(newVal, oldVal) {
      if (newVal !== oldVal) {
      }
    },
  },
  methods: {
    ...mapMutations(["setSearchInput"]),
    //搜索后的根据文件夹路径加载node
    async CellClick(item) {
      this.tableLoading=true;
      console.log("CellClick", item);
      this.expandedKeys = [];
      let _this = this;
      let id = [];
        id.push(item.idArray[0])
        item.idArray.forEach((val,key)=>{
          console.log(key);
          if(key > 0){
            id.push(parseInt(val));
          }
        })
      console.log(id);
      if (sessionStorage.getItem("currentBox") == "我的文档") {
        console.log(item.idArray);
        this.expandedKeys = id;
        this.isloaded = false;
        this.$nextTick(function() {
          this.isloaded = true;
        });
        sessionStorage.setItem("expandedKeys", JSON.stringify(id));
      }  else if (sessionStorage.getItem("currentBox") == "同事共享") {
        this.workmateExpandedKeys = id;
        this.workmateisloaded = false;
        this.$nextTick(function() {
          this.workmateisloaded = true;
        });
      } else if (sessionStorage.getItem("currentBox") == "公司文档") {
        this.companyExpandedKeys = id;
        this.companyisloaded = false;
        this.$nextTick(function() {
          this.companyisloaded = true;
        });
      }
      this.setSearchInput("");
    },
    getIpfs() {
      this.$http.get("/config/getServerList").then(res => {
        let { data } = res;
        console.log(data);
        let iIp,iPort,iPort1;
        let oIp,oPort,oPort1;
        if(data.innerPort!=false){
          iIp = data.innerPort.slice(0, -10);
        iPort = data.innerPort.slice(-9, -5);
        iPort1=data.innerPort.slice(-4)
        }
        if(data.outerPort!=false){
          oIp = data.outerPort.slice(0, -10);
        oPort = data.outerPort.slice(-9, -5);
        oPort1=data.outerPort.slice(-4);
        }
         this.$store.commit('setPortArray',[iIp,oIp]);
        console.log(iIp,':',iPort,':',iPort1)
        console.log(oIp,':',oPort,':',oPort1)
        let inIpfs = ipfsClient({ host: iIp, port: iPort, protocol: "http" });
        let outIpfs = ipfsClient({ host: oIp, port: oPort, protocol: "http" });
        let _this=this;
        inIpfs.id(function(err, identity) {
          if (err) {
            outIpfs.id(function(err, identity) {
              if (err) {
                _this.$store.commit("getIpfsArray", []);
                console.log('aaaaaaaaaaaaaaaa',_this.$store.state.ipfsArray)
              }else{
                _this.$store.commit("getIpfsArray", ['http://'+oIp+':'+oPort+'/api/v0/add?pin=true','http://'+oIp+':'+oPort1+'/',1]);
                console.log('aaaaaaaaaaaaaaaaaa',_this.$store.state.ipfsArray)
              }
            });
          }else{
            _this.$store.commit("getIpfsArray", ['http://'+iIp+':'+iPort+'/api/v0/add?pin=true','http://'+iIp+':'+iPort1+'/',0]);
             console.log('aaaaaaaaaaaaaaaa',_this.$store.state.ipfsArray)
          }
        });
      });
    },
    gotoByPathPar(id){
      console.log(this.nodeInfo);
      if (id == this.nodeInfo.key) {
        return;
      }
      let gotonode = (function getNode(node) {
        let temp;
        if (node.key == id) {
          temp = node;
        } else {
          console.log(node);
          temp = getNode(node.parent);
        }
        return temp;
      })(this.nodeInfo);
      console.log(gotonode);
      this.handlePartnerCollapse(gotonode.data, gotonode);
      gotonode.expanded = false;
      this.handlePartnerExpand(gotonode.data, gotonode);
      gotonode.expanded = true;
    },
    gotoByPathCom(id) {
      console.log(this.nodeInfo);
      if (id == this.nodeInfo.key) {
        return;
      }
      let gotonode = (function getNode(node) {
        let temp;
        if (node.key == id) {
          temp = node;
        } else {
          console.log(node);
          temp = getNode(node.parent);
        }
        return temp;
      })(this.nodeInfo);
      console.log(gotonode);
      this.handleCompanyCollapse(gotonode.data, gotonode);
      gotonode.expanded = false;
      this.handleCompanyExpand(gotonode.data, gotonode);
      gotonode.expanded = true;
    },
    gotoByPath(id) {
      if (id == this.nodeInfo.key) {
        return;
      }
      let gotonode = (function getNode(node) {
        let temp;
        if (node.key == id) {
          temp = node;
        } else {
          temp = getNode(node.parent);
        }
        return temp;
      })(this.nodeInfo);
      this.nodeInfo.isCurrent = false;
      this.nodeInfo = gotonode ;
      this.nodeInfo.isCurrent = true;
      this.handleWorkmateCollapse(gotonode.data, gotonode);
      gotonode.expanded = false;
      this.handleWorkmateExpand(gotonode.data, gotonode);
      gotonode.expanded = true;
    },
    initWorkmate() {
      return new Promise((resolve,reject)=>{
        this.$http.get("/share/getSendName").then(
        res => {
          let { data } = res;
          let children = [];
          if (res.status === 200) {
            console.log(data);
            data.forEach((v, k) => {
              let suffixTemp = v.dirName.split(".");
              let file_icon;
              if (suffixTemp.length > 1) {
                suffixTemp = suffixTemp[suffixTemp.length - 1];
                file_icon = "icon_list_" + suffixTemp;
              } else {
                suffixTemp = null;
              }
              children.push(
                {
                id: v.userId,
                dirName: v.dirName,
                label: v.dirName,
                children: [],
                fileName: v.dirName,
                fileType: 1,
                fileSize: "-",
                creatTime: "-",
                updateTime: "-",
                fileGold: [],
                suffix: suffixTemp
              }
              );
            });
            let obj = {
                  children: children,
                  fileGold:[]
                };
                console.log('objobjobjobjobj',obj);
                resolve(obj);
          }
        },
        err => {
          this.$message({
            message: "网络出错!!",
            type: "error"
          });
          console.log(err);
        }
      );
      })
    },
    getDirList(id) {
      return new Promise((resolve, reject) => {
        console.log('/share/getDirList',id)
        this.$http
          .get("/share/getDirList", {
            params: {
              sendUserId: id
            }
          })
          .then(
            res => {
              console.log("res", res);
              let { data } = res;
              if(data==null){
                let obj = {
                  children: [],
                  fileGold: []
                };
                resolve(obj);
                return;
              }
              console.log("initWorkmateFile", data instanceof Array);
              let children = [];
              let fileGold = [];
              if (res.status === 200) {
                console.log(data);
                data.forEach((v, c) => {
                  if (v.fileType == 1) {
                    v.label=v.fileName;
                    v.vhildren=[];
                    v.fileGold=[];
                    children.push(v);
                  } else {
                    fileGold.push(v);
                  }
                });
                let obj = {
                  children: children,
                  fileGold: fileGold
                };
                resolve(obj);
              }
            },
            err => {
              this.$message({
                message: "网络出错!!",
                type: "error"
              });
              console.log(err);
            }
          );
      });
    },
    clickDir(id) {
      return new Promise((resolve, reject) => {
        this.$http
          .post("/file/clickdir", {
              id: id
          })
          .then(
            res => {
              console.log("res", res);
              let { data } = res;
              if(data==null){
                let obj = {
                  children: [],
                  fileGold: []
                };
                resolve(obj);
                return;
              }
              let children = [];
              let fileGold = [];
              if (res.status === 200) {
                console.log(data);
                data.forEach((v, c) => {
                  if (v.fileType == 1) {
                    v.label=v.fileName;
                    v.vhildren=[];
                    v.fileGold=[];
                    children.push(v);
                  } else {
                    fileGold.push(v);
                  }
                });
                let obj = {
                  children: children,
                  fileGold: fileGold
                };
                resolve(obj);
              }
            },
            err => {
              this.$message({
                message: "网络出错!!",
                type: "error"
              });
              reject("err");
            }
          );
      });
    },
    handlePartnerCollapse(data, node, self) {
      //节点合上时，将子节点全部合上。
      if (node.childNodes != false) {
        node.childNodes.forEach(val => {
          val.expanded = false;
        });
      }
    },
    handlePartnerClick(data, node){
      if(node.childNodes==false){
        this.handlePartnerExpand(data,node);
      }
    },
    handleCompanyClick(data, node) {
      if(node.childNodes==false){
        this.handleCompanyExpand(data,node);
      }
    },
    handleCompanyCollapse(data, node, self) {
      //节点合上时，将子节点全部合上。
      if (node.childNodes != false) {
        node.childNodes.forEach(val => {
          val.expanded = false;
        });
      }
    },
    async handlePartnerExpand(data, node, comp) {
      this.setSearchInput("");
      sessionStorage.setItem("currentBox", "合作伙伴");
      this.$store.state.placeHolder = "搜索合作伙伴";
      console.log(node);
      this.nodeInfo.isCurrent = false;
      this.nodeInfo = node;
      this.nodeInfo.isCurrent = true;
      let obj;
      if(node.level==1){
        obj=await this.getAllCompany();
      }else{
        obj=await this.GetPartner(node.data);
      }
      // 将数据传给表格
      if(this.tableLoading==false){
        this.partnerExpandedKeys=[];
      }
      if(this.partnerExpandedKeys==false || node.data.id == this.partnerExpandedKeys[this.partnerExpandedKeys.length-1]){
        console.log(obj.fileGold);
        if (obj.fileGold == false) {
          this.fileDetails = obj.children;
        } else {
          this.fileDetails = obj.children.concat(obj.fileGold);
        }
      }
      //递归节点 获取url数组
      this.fileUrl = this.handleFileUrl3(node);
      console.log(this.fileUrl)
    },
    async handleCompanyExpand(data, node, comp) {
      this.setSearchInput("");
      sessionStorage.setItem("currentBox", "公司文档");
      this.$store.state.placeHolder = "搜索公司文档";
      console.log(node);
      this.nodeInfo.isCurrent = false;
      this.nodeInfo = node;
      this.nodeInfo.isCurrent = true;
      let obj;
      if(node.level==1){
        obj=await this.GetCompany();
      }else{
        obj=await this.clickDir(node.data.id);
      }
      // 将数据传给表格
      if(this.tableLoading==false){
        this.companyExpandedKeys=[]
      }
      if(this.companyExpandedKeys==false||node.data.id == this.companyExpandedKeys[this.companyExpandedKeys.length-1]){
        if (obj.fileGold == false) {
        this.fileDetails = obj.children;
      } else {
        this.fileDetails = obj.children.concat(obj.fileGold);
      }
      }
      //递归节点 获取url数组
      this.fileUrl = this.handleFileUrl2(node);
    },
    handleWorkmateClick(data, node) {
      if(node.childNodes==false){
        this.handleWorkmateExpand(data,node);
      }
    },
    handleWorkmateCollapse(data, node, self) {
      //节点合上时，将子节点全部合上。
      this.nodeInfo.isCurrent=false;
      this.nodeInfo=node;
      this.nodeInfo.isCurrent=true;
      if (node.childNodes != false) {
        node.childNodes.forEach(val => {
          val.expanded = false;
          val.isCurrent=false;
        });
      }
    },
    async handleWorkmateExpand(data, node, comp) {
      //子层数据传给表格
     this.setSearchInput("");
     sessionStorage.setItem("currentBox", "同事共享");
     this.$store.state.placeHolder = "搜索同事共享";
        this.nodeInfo.isCurrent = false;
      this.nodeInfo = node;
      this.nodeInfo.isCurrent = true;
      let obj;
      if(node.level==1){
        obj=await this.initWorkmate();
      }else if(node.level==2){
        console.log(node);
        sessionStorage.setItem("tempUserDirId",node.key);
        obj=await this.getDirList(node.key);
      }else{
        obj=await this.clickDir(node.key);
      }
      // 将数据传给表格
      if(this.tableLoading==false){
        this.workmateExpandedKeys=[];
      }
      if(this.workmateExpandedKeys==false || node.data.id == this.workmateExpandedKeys[this.workmateExpandedKeys.length-1]){
        if (obj.fileGold == false) {
        this.fileDetails = obj.children;
      } else {
        this.fileDetails = obj.children.concat(obj.fileGold);
      }
      }
      //递归节点 获取url数组
      this.fileUrl = this.handleFileUrl1(node);
    },
    // 同事共享树的懒加载绑定函数
    async loadedWFNode(node,resolve){
      console.log(node);
      this.resolveCallBack = resolve;
      resolve=this.resolveCallBack;
      //获取子节点
      let obj;
      if (node.data.label == undefined) {
        console.log('1111111111111')
        obj={
          children:[],
          fileGold:[],
        }
        resolve(this.workmateData)
        return;
      }else if(node.level==1){
        console.log('222222222222')
        obj=await this.initWorkmate();
        resolve(obj.children)
      }else if(node.level==2){
        console.log('3333333333333333')
        obj=await this.getDirList(node.data.id);
        resolve(obj.children)
      }else{
        console.log('1444444444444')
        obj=await this.clickDir(node.data.id);
        resolve(obj.children)
      }
      // 将数据传给表格
      if(this.workmateExpandedKeys==false || node.data.id == this.workmateExpandedKeys[this.workmateExpandedKeys.length-1]){
        if (obj.fileGold == false) {
          this.fileDetails = obj.children;
        } else {
          this.fileDetails = obj.children.concat(obj.fileGold);
        }
      }
      console.log(this.fileDetails)
      // 获取url
      this.fileUrl = this.handleFileUrl1(node);
      this.nodeInfo.isCurrent=false;
      this.nodeInfo=node;
      this.nodeInfo.isCurrent=true;
      // 搜索结果点击后最终结果处理
      console.log(node.data.id);
      console.log(this.workmateExpandedKeys)
      if(node.data.id == this.workmateExpandedKeys[this.workmateExpandedKeys.length-1]){
        this.tableLoading=false;
        this.workmateExpandedKeys=[];
      }
    },
    gotoMyCollection() {
      this.isCollectClick = true;
      this.isFileDetails = false;
    },
    //添加文件夹
    appendChildNode(node) {
      let { childNode, parentNode } = node;
      console.log("appendChildNode", childNode, parentNode);
      if (this.nodeInfo.label == "我的文档" || this.nodeInfo.label == undefined) {
        parentNode.loaded = false
        if (this.nodeInfo.data.children == false) {
          this.nodeInfo.data.children = [{}];
        }
        this.expandedKeys = [parseInt(localStorage.getItem("dirId"))];
      }else {
        parentNode.expanded = false;
        parentNode.loaded = false;
        parentNode.childNodes = [];
        parentNode.data.children = [];
        this.expandedKeys = [parseInt(localStorage.getItem("dirId"))];
        this.expandedKeys.push(childNode.dirId); //使得tree刷新数据
      }

    },
    //文件夹路径点击
    loadedTheNode(nodeResolve) {
      let { node, resolve } = nodeResolve;
      if(node.label == undefined){
        return;
      }
      console.log("loadedTheNode", node, resolve);
      node.isCurrent = true;
      node.expanded = false;
      node.childNodes = [];
      node.data.children = [];
      if (node.label == "我的文档" || node.label == undefined) {
        if(node.label == "我的文档"){
          this.reloadFolders();
          return;
        }
        console.log("aaaaaaaaaaa");
        node.loaded = false;
        this.expandedKeys = [localStorage.getItem("dirId")];
      } else {
        node.loaded = false;
        this.loadNode(node);
      }
    },
    //处理删除文件夹和上传文件 刷新文件树 handel-del-file && handel-upload-file
    refreshTreeData(nodeData) {
      if (this.nodeInfo.label == "我的文档" || this.nodeInfo.label == undefined) {
        let {currNode, nodeInfo, resolveCallBack} = nodeData
        nodeInfo.loaded = false
        if (this.nodeInfo.data.children == false) {
          this.nodeInfo.data.children = [{}];
        }
        this.expandedKeys = [parseInt(localStorage.getItem("dirId"))];
      }else {
        let temp = this.nodeInfo;
        temp.expanded = false;
        temp.loaded = false;
        temp.childNodes = [];
        temp.data.children = [];
        this.expandedKeys = [parseInt(localStorage.getItem("dirId"))];
        this.expandedKeys.push(temp.key); //使得tree刷新数据
      }
    },
    //文件夹名称点击
    setExpandedKeys(data) {
      let {row, nodeData} = data
      let {currNode, nodeInfo, resolveCallBack} = nodeData
      let id = row.id;
      console.log('setExpandedKeys==data==', data);
      console.log(this.fileUrl);
      if (this.fileUrl[0].label == "同事共享") {
        console.log("setExpandedKeys------", row);
        this.workmateExpandedKeys= [0];
        this.workmateExpandedKeys.push(id); //点击table item 使得tree刷新数据
        let foundIt = this.nodeInfo.childNodes.find(function(element) {
          return element.key == row.id;
        });
        if (!foundIt.isCurrent) foundIt.isCurrent = true;
        console.log("setExpandedKeys", this.workmateExpandedKeys);
        console.log("nodeInfo>>>", this.nodeInfo, foundIt);
        this.handleWorkmateExpand(foundIt.data,foundIt);
        return this.workmateExpandedKeys;
      } else if(this.fileUrl[0].label == "我的文档"){
        console.log("setExpandedKeys------", row);
        if (this.nodeInfo.label == undefined ) {
          this.expandedKeys = [parseInt(localStorage.getItem("dirId"))];   // 3136
          this.folderId = id
          console.log("setExpandedKeys", this.expandedKeys);
        }else {
          this.expandedKeys = [parseInt(localStorage.getItem("dirId"))];
          this.expandedKeys.push(id); //点击table item 使得tree刷新数据
          console.log("setExpandedKeys", this.expandedKeys);
          let foundIt = this.nodeInfo.childNodes.find(function(element) {
            return element.key == row.id;
          });
          console.log("nodeInfo>>>", this.nodeInfo, foundIt);
          if (!foundIt.isCurrent) foundIt.isCurrent = true;
        }
      }else if(this.fileUrl[0].label == "公司文档"){
        this.companyExpandedKeys= [0];
        this.companyExpandedKeys.push(id); //点击table item 使得tree刷新数据
        let foundIt = this.nodeInfo.childNodes.find(function(element) {
          return element.key == row.id;
        });
        if (!foundIt.isCurrent) foundIt.isCurrent = true;
        console.log("setExpandedKeys", this.companyExpandedKeys);
        console.log("nodeInfo>>>", this.nodeInfo, foundIt);
        this.handleCompanyExpand(foundIt.data,foundIt);
        return this.companyExpandedKeys;
      }else if(this.fileUrl[0].label == "合作伙伴"){
        this.partnerExpandedKeys= [0];
        this.partnerExpandedKeys.push(id); //点击table item 使得tree刷新数据
        let foundIt = this.nodeInfo.childNodes.find(function(element) {
          return element.key == row.id;
        });
        if (!foundIt.isCurrent) foundIt.isCurrent = true;
        console.log("setExpandedKeys", this.partnerExpandedKeys);
        console.log("nodeInfo>>>", this.nodeInfo, foundIt);
        this.handlePartnerExpand(foundIt.data,foundIt);
        return this.partnerExpandedKeys;
      }
      return this.expandedKeys;
    },
    handleNodeClick(data, node, comp) {
      this.isCollectClick = false;
      this.currFileId = data.id;
      this.nodeTemp = data;
      this.currNode = node;
      //data.children == undefinded 空文件夹时清空fileDetails
      if (!data.children) {
        data.children = [];
        this.fileDetails = [];
        node.loaded = false;
        this.fileDetails.$nodeAndresolve = function() {
          return { node, resolveFun: null };
        };
      } else {
        node.isLeaf = false;
        node.loaded = false;
        node.expanded = false;
      }
      console.log("handleNodeClick==", data, node);
    },
    handleNodeCollapse(data, node, comp) {
      node.loaded = false;
      if (data.label == "我的文档") {
        this.expandedKeys = []
      }
      console.log("handleNodeCollapse==", data, node);
    },
    handleNodeExpand(data, node, comp) {
      this.setSearchInput("");
      sessionStorage.setItem("currentBox", "我的文档");
      this.$store.state.placeHolder = "搜索我的文档文件/文件夹";
      console.log("handleNodeClick ids", this.dataTemp.id, data.id);
      if (this.dataTemp.id !== data.id || this.dataTemp.id !== undefined) {
        node.childNodes = [];
        data.children = [];
        node.loaded = false;
      }
      this.currFileId = data.id;
      this.dataTemp = data;
      this.nodeTemp = data;
      this.currNode = node;
      console.log("handleNodeExpand", data, node, comp);
    },
    handleFileUrl(node) {
      let pathArr = [];
      this.keysForId = [];
      let _this = this;
      !(function getCurrentPart(info) {
        if (!info.resolve) {
          info = { node: info };
        }
        let result;
        if (info.node.label == "我的文档" || info.node.label == undefined) {
          result = info;
          pathArr.push({ label: "我的文档", nodeResolve: info });
          _this.keysForId.push(localStorage.getItem("dirId"));
        } else if (info.node.label == "同事共享") {
          result = info;
          pathArr.push({ label: "同事共享", nodeResolve: info });
          _this.keysForId.push(0);
        } else {
          pathArr.push({ label: info.node.label, nodeResolve: info });
          _this.keysForId.push(info.node.key);
          result = getCurrentPart({node: info.node.parent, resolve: info.resolve});
        }
        return result;
      })(node);
      this.keysForId.reverse();
      return pathArr.reverse();
    },
    handleFileUrl1(node) {
      let pathArr = [];
      this.keysForId = [];
      let _this = this;
      !(function getCurrentPart(node) {
        let result;
        if (node.label == "同事共享") {
          result = node;
          pathArr.push({ label: "同事共享" });
          _this.keysForId.push(0);
        } else {
          pathArr.push({ label: node.label });
          _this.keysForId.push(node.key);
          result = getCurrentPart(node.parent);
        }
        return result;
      })(node);
      console.log("================pathArr", pathArr);
      this.keysForId.reverse();
      return pathArr.reverse();
    },
    handleFileUrl3(node) {
      let pathArr = [];
      this.keysForId = [];
      let _this = this;
      console.log(node);
      !(function getCurrentPart(node) {
        let result;
        if (node.label == "合作伙伴") {
          result = node;
          pathArr.push({ label: "合作伙伴" });
          _this.keysForId.push(0);
        } else {
          pathArr.push({ label: node.label });
          _this.keysForId.push(node.key);
          result = getCurrentPart(node.parent);
        }
        return result;
      })(node);
      console.log("================pathArr", pathArr);
      this.keysForId.reverse();
      return pathArr.reverse();
    },
    handleFileUrl2(node) {
      let pathArr = [];
      this.keysForId = [];
      let _this = this;
      !(function getCurrentPart(node) {
        let result;
        if (node.label == "公司文档") {
          result = node;
          pathArr.push({ label: "公司文档" });
          _this.keysForId.push(0);
        } else {
          pathArr.push({ label: node.label });
          _this.keysForId.push(node.key);
          result = getCurrentPart(node.parent);
        }
        return result;
      })(node);
      console.log("================pathArr", pathArr);
      this.keysForId.reverse();
      return pathArr.reverse();
    },
    //返回上一级
    handleParentNode(data) {
      let label = sessionStorage.getItem("currentBox");
      console.log(this.nodeInfo)
      if (label == "同事共享") {
        if(this.nodeInfo.level==1){
          return;
        }
        this.handleWorkmateCollapse(
          this.nodeInfo.data,
          this.nodeInfo
        );
        this.nodeInfo.expanded=false;
          this.handleWorkmateExpand(
          this.nodeInfo.parent.data,
          this.nodeInfo.parent
        );
      }else if(label == "公司文档"){
        console.log(this.nodeInfo);
        if(this.nodeInfo.level==1){
          return;
        }
        this.handleCompanyCollapse(
          this.nodeInfo.data,
          this.nodeInfo
        );
        this.nodeInfo.expanded = false;
        this.handleCompanyExpand(
          this.nodeInfo.parent.data,
          this.nodeInfo.parent
        );
      }else if(label == "合作伙伴"){
        console.log(this.nodeInfo);
        if(this.nodeInfo.level==1){
          return;
        }
        this.handlePartnerCollapse(
          this.nodeInfo.data,
          this.nodeInfo
        );
        this.nodeInfo.expanded = false;
        this.handlePartnerExpand(
          this.nodeInfo.parent.data,
          this.nodeInfo.parent
        );
      } else {
          let {node} = data();
          let para = null;
          console.log("返回上一级：", node);
          if (node.label !== "我的文档" && node.label !== undefined) {
            this.expandedKeys.splice(-1);
            this.fileUrl = this.handleFileUrl(node);
            if (node.level == 2) {
              sessionStorage.removeItem("expandedKeys")
              this.folderId = ''  //用来存储根节点默认收起时的文件夹名称点击的id
              node.parent.childNodes = [];
              node.parent.data.children = [];
              node.parent.loaded = false;
              node.parent.expanded = false;
            } else {
              node.parent.childNodes = [];
              node.parent.loaded = false;
              node.parent.isCurrent = false;
              node.parent.expanded = false;
              node.isCurrent = false;
              node.expanded = false;
              this.loadNode(node.parent);
            }
          }
        }
    },
    // async loadPartnerNode(node,resolve){
    //   console.log(node);
    //   this.resolveCallBack = resolve;
    //   resolve=this.resolveCallBack;
    //   //获取子节点
    //   let obj;
    //   if (node.data.label == undefined) {
    //     obj = {
    //       children: [],
    //       fileGold: [],
    //     }
    //     resolve(this.partnerData)
    //     return;
    //   }else if(node.level == 1){
    //     obj = await this.getAllCompany();
    //     resolve(obj.children)
    //   }else{
    //     obj=await this.GetPartner(node.data);
    //     resolve(obj.children)
    //   }
    //   if(this.partnerExpandedKeys==false||node.data.id == this.partnerExpandedKeys[this.partnerExpandedKeys.length-1]){
    //     if (obj.fileGold == false) {
    //       this.fileDetails = obj.children;
    //     } else {
    //       this.fileDetails = obj.children.concat(obj.fileGold);
    //     }
    //   }
      // 获取url
      // this.fileUrl = this.handleFileUrl3(node);
      // 修改当前选中节点，并改变样式
    //   this.nodeInfo.isCurrent = false;
    //   this.nodeInfo = node;
    //   this.nodeInfo.isCurrent = true;
    //   if(node.data.id == this.partnerExpandedKeys[this.partnerExpandedKeys.length-1]){
    //     console.log("ffffffffffffffffffffffffff")
    //     this.partnerExpandedKeys=[];
    //     this.tableLoading=false;
    //   }
    // },
    async loadCompanyNode(node,resolve){
      console.log(node);
      this.resolveCallBack = resolve;
      resolve=this.resolveCallBack;
      //告诉系统当前展开的是同事分享树
      this.setSearchInput("");
      //获取子节点
      let obj;
      if (node.data.label == undefined) {
        console.log("aaaaaaaaaa1111111111")
        obj = {
          children: [],
          fileGold: [],
        }
        resolve(this.companyData)
        return;
      }else if(node.level == 1){
        console.log("aaaaaaaaaa222222222")
        obj = await this.GetCompany();
        console.log(obj);
        resolve(obj.children)
      }else{
        console.log("aaaaaaaaaa3333333333")
        obj=await this.clickDir(node.data.id);
        resolve(obj.children)
      }
      if(this.companyExpandedKeys==false||node.data.id == this.companyExpandedKeys[this.companyExpandedKeys.length-1]){
        if (obj.fileGold == false) {
        this.fileDetails = obj.children;
      } else {
        this.fileDetails = obj.children.concat(obj.fileGold);
      }
      }
      // 获取url
      this.fileUrl = this.handleFileUrl2(node);
      // 修改当前选中节点，并改变样式
      this.nodeInfo.isCurrent = false;
      this.nodeInfo = node;
      this.nodeInfo.isCurrent = true;
      if(node.data.id == this.companyExpandedKeys[this.companyExpandedKeys.length-1]){
        this.companyExpandedKeys=[];
        this.tableLoading=false;
      }
    },
    getAllCompany(){
      return new Promise((resolve, reject) => {
        this.$http.get('/company/getCompanyList').then(res=>{
          let {data}=res;
          console.log(res);
          let company=[];
          if(res.status==200){
            data.forEach(val=>{
              company.push({
                id: val.id,
                fileName: val.name,
                creatTime: val.createTime,
                updateTime: '-',
                fileSize:'-',
                label: val.name,
                fileType:1,
                identity:val.identity
              })
            })
            let obj = {
              children: company,
              fileGold:[]
            };
            resolve(obj);
          }
        })
      })
    },
    GetPartner(node){
      return new Promise((resolve, reject) => {
        // node.identity
        this.$http.get("/chainShare/getShareList",{
          params:{
            fromAccount:node.identity
          }
        }).then(
          res => {
            console.log(node);
            console.log("res", res);
            let { data } = res;
            if(data==null){
              let obj = {
                children: [],
                fileGold: []
              };
              resolve(obj);
              return;
            }
            let children = [];
            let fileGold = [];
            if (res.status === 200) {
              console.log(data);
              data.forEach((v, c) => {
                v.creatTime=v.createTime;
                v.fileType=0;
                v.updateTime='-'
                fileGold.push(v);
              });
              let obj = {
                children: children,
                fileGold: fileGold
              };
              resolve(obj);
            }
          },
          err => {
            this.$message({
              message: "网络出错!!",
              type: "error"
            });
            console.log(err);
          }
        )
      })
    },
    GetCompany(){
      return new Promise((resolve, reject) => {
        this.$http.get("/companyFile/getCompanyFile").then(
          res => {
            console.log("res", res);
            let { data } = res;
            if(data==null){
              let obj = {
                children: [],
                fileGold: []
              };
              resolve(obj);
              return;
            }
            console.log("initWorkmateFile", data instanceof Array);
            let children = [];
            let fileGold = [];
            if (res.status === 200) {
              console.log(data);
              data.forEach((v, c) => {
                v.id=v.fileId
                if (v.fileType == 1) {
                  v.label=v.fileName;
                  v.children=[];
                  v.fileGold=[];
                  children.push(v);
                } else {
                  fileGold.push(v);
                }
              });
              // if (k.children.length == 0) {
              //   k.isclick = true;
              // }
              let obj = {
                children: children,
                fileGold: fileGold
              };
              resolve(obj);
            }
          },
          err => {
            this.$message({
              message: "网络出错!!",
              type: "error"
            });
            console.log(err);
          }
        )
      })
    },
    async loadNode(node, resolve) {
      console.log("文件夹节点：", node);
      console.log("文件夹路径：", this.fileUrl);
      // 路径
      this.fileUrl = this.handleFileUrl({ node: node, resolve: resolve });
      // 清空子节点 我的文档展开时在我的文档添加文件夹时先清空子节点
      if (node.data.children && JSON.stringify(node.data.children[0]) == "{}") {
        node.data.children.splice(0, 1);
        node.childNodes.splice(0, 1);
        node.isLeaf = false;
        node.expanded = false;
      }
      if(sessionStorage.getItem("expandedKeys") != null){
        this.expandedKeys = JSON.parse(sessionStorage.getItem("expandedKeys"));
      }else{
        this.expandedKeys = [localStorage.getItem("dirId")];
        this.expandedKeys.push(node.data.id);
      }
      this.nodeInfo.isCurrent = false;
      this.nodeInfo = node;
      console.log("!!!!!!!!!!!!!!",this.nodeInfo,this.expandedKeys[this.expandedKeys.length-1])
      if(node.data.id == this.expandedKeys[this.expandedKeys.length-1]){
        sessionStorage.removeItem("expandedKeys");
        this.tableLoading=false;
      }
      this.nodeInfo.isCurrent = true;
      this.resolveCallBack = resolve;
      this.currFileId = node.data.id;
      let folders = [];
      let fileList = [];
      if (node.level == 0) {
        if(sessionStorage.getItem("expandedKeys")==undefined){
          this.expandedKeys = []
        }
        fileList = await this.$http.get("/file/ls");
        console.log("===========fileList===", fileList);
        if (fileList.status === 200 && fileList.data !== null) {
          if(sessionStorage.getItem("expandedKeys")==undefined || node.data.dirId == this.expandedKeys[this.expandedKeys.length-1]){
            this.fileDetails = fileList.data; //传给fileDetails组件
          }
        }else {
          this.fileDetails = [];
        }
      }else if (!node.expanded) {
        //if 加载二级节点
        // else 加载二级节点子节点
        if (node.data.label == "我的文档" || node.data.label == undefined) {
          this.dataFile[0].children = [];
          fileList = await this.$http.get("/file/ls");
          console.log("===========fileList===", fileList.data);
          if (fileList.status === 200 && fileList.data !== null) {
            if(sessionStorage.getItem("expandedKeys") == undefined || node.data.id == this.expandedKeys[this.expandedKeys.length-1]){
            this.fileDetails = fileList.data; //传给fileDetails组件
          }
            let arr = []
            for (let item of fileList.data) {
              if (item.fileType === 1) {
                arr.push({
                  id: item.id,
                  dirId: item.dirId,
                  label: item.fileName,
                  type: item.fileType,
                  leaf: false,
                  children: [{}],
                  resolveNode: function() {
                    return { node, resolveFun };
                  }
                });
              }
              console.log("111111111111");
              folders = arr
            }
          }else {
            this.fileDetails = [];
          }
          if (node.level == 1 && this.folderId !== '' && !node.expanded) {
            this.expandedKeys = [1, this.folderId]
          }
        } else {
          let tempInfo = [];
          fileList = await this.$http.post("/file/clickdir", {
            id: node.data.id
          });
          console.log("===========fileList===", fileList.data);
          if (fileList.status === 200 && fileList.data !== null) {
            if(sessionStorage.getItem("expandedKeys")==undefined || node.data.id == this.expandedKeys[this.expandedKeys.length-1]){
            this.fileDetails = fileList.data; //传给fileDetails组件
          }; //传给fileDetails组件
            let arr = []
            for (let item of fileList.data) {
              if (item.fileType === 1) {
                arr.push({
                  id: item.id,
                  dirId: item.dirId,
                  label: item.fileName,
                  type: item.fileType,
                  leaf: false,
                  children: [{}],
                  resolveNode: function() {
                    return { node, resolveFun };
                  }
                });
              }
            }
            console.log("222222222222222");
            folders = arr
          } else if (fileList.status === 200 && fileList.data == null) {
            folders = [];
            this.fileDetails = [];
          }
        }
      }
      this.fileDetails.$nodeAndresolve = function() {
        return { node, resolveFun: resolve };
      };
      console.log("loadNode fileDetails", this.fileDetails);
      if (node.data.label == undefined) {
        let arr = this.dataFile;
        arr[0].children;
        resolve(arr);
      } else {
        console.log('====folders=========',folders);
        resolve(folders);
      }
    },
    //依次检查文件夹的子文件夹是否为空文件夹
    checkFolders(item, arr, obj) {
      console.log("checkFolders");
      let temp = []; //检查是否有文件夹
      let temp1 = []; //检查是否有文件
      let _this = this;
      return new Promise((resolve, reject) => {
        this.$http.post("/file/clickdir", { id: item.id }).then(
          res => {
            let { node, resolveFun } = obj;
            let { data, status } = res;
            //依次检查文件夹的子文件夹是否为空文件夹
            if (status === 200 && data !== null) {
              // 如果文件夹的子文件夹不为空 把不同类型的数据存起来
              data.forEach(value => {
                if (value.fileType === 1) {
                  temp.push(value);
                } else {
                  temp1.push(value);
                }
              });
              //根据不同类型数据是否为空来判断它是否该产生子文件夹
              if (temp == false) {
                if (!(temp1 == false)) {
                  // temp1 不为空
                  arr.push({
                    id: item.id,
                    dirId: item.dirId,
                    label: item.fileName,
                    type: item.fileType,
                    children: [{}],
                    resolveNode: function() {
                      return { node, resolveFun };
                    }
                  });
                }
              } else {
                // temp 不为空
                arr.push({
                  id: item.id,
                  dirId: item.dirId,
                  label: item.fileName,
                  type: item.fileType,
                  children: [{}],
                  resolveNode: function() {
                    return { node, resolveFun };
                  }
                });
              }
            } else {
              arr.push({
                id: item.id,
                dirId: item.dirId,
                // label: item.fileName + '(空)',
                label: item.fileName,
                type: item.fileType,
                leaf: true,
                children: [{}],
                resolveNode: function() {
                  return { node, resolveFun };
                }
              });
            }
            resolve(arr);
          },
          err => {
            alert("请检查网络，网络错误...");
            reject(err);
          }
        );
      });
    },
    reloadFolders() {
      this.isRouterAlive = false;
      this.$nextTick(function() {
        this.isRouterAlive = true;
      });
    },
    //文件图标 css在app.vue中
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>
            <span class="folders document" />
            {node.label}
          </span>
        </span>
      );
    },
    reloadFileDetails() {
      this.isFileDetails = false;
      this.$nextTick(function() {
        this.isFileDetails = true;
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "scss_vars";

#folderPage {
  position: absolute;
  margin-left: 120px;
  top: 80px;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;

  .el-aside {
    flex: 0 0 200px;
    height: 100%;
    width: 200px !important;
    background: $main-bg;
    overflow-y: auto;
    overflow-x: auto;
    border-right: 1px solid $black-bg;

    .collection {
      margin-top: 15px;
      white-space: nowrap;
      width: auto;
      padding: 2px 10px;
      font-weight: 500;
      margin-bottom: 14px;
      cursor: pointer;
      i {
        font-size: 16px;
        margin-left: 30px;
        margin-right: 5px;
        color: #f8cb00;
      }
      .collect {
        color: #549de8;
      }
      .active {
        display: inline-block;
        background: #dbe4eb;
      }
    }
  }

  .el-main {
    flex: 1;
    overflow-y: scroll;
    background: white;
    padding: 0;
  }
}
</style>
<style lang="scss">
@import "scss_vars";
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  color: $aside-bg;
  background: none;
}
#folderPage {
  display: flex;
  position: absolute;
  top: 90px;
  bottom: 0;
  overflow: hidden;
  .el-tree-node__content:hover{
      background: none;
  }
  .el-tree-node__content:focus{
      background: none;
  }
  .el-tree-node:focus > .el-tree-node__content {
      background: none;
  }
  aside {
    flex: 0 0 200px;
    height: 100%;
    width: 200px !important;
    border-right: 1px solid #e4e4e4;
    overflow-y: auto;
    overflow-x: auto;
    .menu-expanded {
      flex: 0 0 200px;
      width: 200px !important;
      overflow-x: auto;
    }
    .el-tree {
      min-width: 100%;
      display: inline-block !important;
    }
  }
  .folders {
    width: 20px;
    height: 20px;
    background: url("../assets/icon/file-icon.png") no-repeat;
  }
}
</style>
